/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml.timgiayto.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import xml.timgiayto.binding.info.Information;
import xml.timgiayto.utils.CommonUtils;
import xml.timgiayto.utils.DBUtils;

/**
 *
 * @author mrnghiep
 */
public class UploadController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            if (!isMultiPart) {
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException ex) {
                    Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
                }

                Iterator iter = items.iterator();
                Hashtable params = new Hashtable();
                String fileName = null;
                String imageUrl = null;

                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        params.put(item.getFieldName(), item.getString());
                    } else {
                        try {
                            String itemName = item.getName();
                            fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                            String realPath = getServletContext().getRealPath("/") + "images\\upload" + "\\" + fileName;
                            imageUrl = "images/upload/" + fileName;
                            // Check if don't have image, default.jpg will used.
                            if ("".equals(fileName)) {
                                imageUrl = "images/upload/card.png";
                            }
                            File saveFile = new File(realPath);
                            item.write(saveFile);
                        } catch (Exception e) {
                        }
                    }
                } // End while
                String fullName = CommonUtils.convertUTF8((String) params.get("txtFullname"));
                String address = CommonUtils.convertUTF8((String) params.get("txtAddress"));
                String email = (String) params.get("txtEmail");
                String phone = (String) params.get("txtPhone");
                String info = CommonUtils.convertUTF8((String) params.get("txtInfo"));
                String type = CommonUtils.convertUTF8((String) params.get("txtType"));
                String location = CommonUtils.convertUTF8((String) params.get("txtLocation"));
                String owner = CommonUtils.convertUTF8((String) params.get("txtOwner"));
                String description = CommonUtils.convertUTF8((String) params.get("txtDescription"));
                String category = (String) params.get("txtCate");
                String status = "";
                if (category.equals("L")) {
                    category = "L";
                    status = "Bạn đã đăng tin thành công, chúc bạn sớm tìm lại được giấy tờ!";
                } else {
                    category = "C";
                    status = "Bạn đã đăng tin thành công, cảm ơn bạn rất nhiều, chúc bạn luôn may mắn!";
                }
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat dayFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                String date = dayFormat.format(calendar.getTime());

                // New object Information
                Information information = new Information(fullName, address, phone, email, info, type,
                        location, owner, imageUrl, description, date, category);

                // Call function to insert to database
                boolean result = DBUtils.createInformation(information);
                HttpSession session = request.getSession();
                if (result) {
                    session.setAttribute("STATUS", status);
                } else {
                    session.setAttribute("STATUS", "Lỗi khi đăng tin, vui lòng thử lại sau.");
                }

                response.sendRedirect("Info?action=marshall&currentUrl=" + CommonUtils.CREATE_PATH + "?type=" + category);

            } // End else
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
